package com.yanxi.user.web.config;

import com.yanxi.user.web.common.util.ManagedChannelUtils;
import com.yanxi.user.web.grpc.RegisterService.RegisterRequest;
import com.yanxi.user.web.grpc.RegisterService.RegisterResponse;
import com.yanxi.user.web.grpc.RegisterService.RegisterServiceGrpc;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.logging.Logger;

@Component
public class LaunchRegiter {

    /**
     * 如果是 gRPC 调用的话一点得是 gRPC 端口号
     */
    @Value("${grpc.server.port}")
    private String port;

    @Value("${server.name}")
    private String projectName;

    @Value("${grpc.client.xyregiserve.port}")
    private String regiservePort;

    @Value("${grpc.client.xyregiserve.url}")
    private String regiserveUrl;


    /**
     * gRPC 方法名 或者 标识 ; 理解原理根据自己的项目配置
     * http 就是接口名
     */
    private final String callbackInterface = "";

    /**
     * 不一定是内网地址，也可以是代理..根据自身架构来配置。
     */
    private String inNetIp = "localhost";

    private static final Logger logger = Logger.getLogger(LaunchRegiter.class.getName());

    /**
     * 注册服务
     */
    @PostConstruct
    public void registerService(){

        ManagedChannelUtils.runWithManagedChannel(regiserveUrl, regiservePort, channel -> {

            RegisterServiceGrpc.RegisterServiceBlockingStub registerServiceBlockingStub = RegisterServiceGrpc.newBlockingStub(channel);

            /**
             * 注册
             */
            RegisterResponse registerResponse = registerServiceBlockingStub.registerClient(RegisterRequest
                    .newBuilder()
                    .setCallbackInterface(callbackInterface)
                    .setInNetIp(inNetIp)
                    .setPort(port)
                    .setProjectName(projectName)
                    .build());

            /**
             * 注册成功
             */
            if(registerResponse.getStatus()==200){

                logger.info("Server Register Success ૮(˶ᵔ ᵕ ᵔ˶)ა ");

            }else{

                logger.warning("Server Register Error (˚ ˃̣̣̥᷄⌓˂̣̣̥᷅ ) ");
                throw new RuntimeException("Server Register Error (˚ ˃̣̣̥᷄⌓˂̣̣̥᷅ )");

            }
        });

    }

}


